<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Student List Management</title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }

    table,
    th,
    td {
      border: 1px solid black;
    }

    th,
    td {
      padding: 8px;
      text-align: left;
    }

    th {
      background-color: #f2f2f2;
    }

    /* 弹框样式 */
    .modal {
      display: none;
      /* 初始隐藏 */
      position: fixed;
      z-index: 1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgb(0, 0, 0);
      background-color: rgba(0, 0, 0, 0.4);
    }

    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 300px;
    }

    .modal-content label {
      display: block;
      margin-bottom: 5px;
    }

    .modal-content input[type="text"],
    .modal-content input[type="number"],
    .modal-content select {
      width: 100%;
      padding: 8px;
      margin-bottom: 10px;
      box-sizing: border-box;
    }

    .modal-content button {
      width: 100%;
      padding: 10px;
      background-color: #4CAF50;
      color: white;
      border: none;
      cursor: pointer;
    }

    .modal-content button:hover {
      background-color: #45a049;
    }

    .rf {
      float: right;
    }
  </style>
</head>

<body>

  <h2>Student List Management</h2>
  <button class="openModalBtn">Add New Student</button>
  <button class="rf search">search</button>
  <input type="text" name="searchname" class="rf searchname" required>
  <table class="studentTable">
    <thead>
      <tr>
        <th><input type="checkbox" class="selectAll"></th>
        <th>ID</th>
        <th>Name</th>
        <th>Gender</th>
        <th>Hobbies</th>
        <th>Age</th>
        <th>PhoneNumber</th>
        <th>Email</th>
        <th>CreateTime</th>
        <th>UpdateTime</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <!-- Student rows will be added dynamically here -->
    </tbody>
  </table>

  <!-- 添加/修改学生信息的弹框 -->
  <div class="studentModal modal">
    <div class="modal-content">
      <h3 class="modalTitle">Add New Student</h3>
      <form class="studentForm">
        <input type="hidden" class="studentIdToEdit"> <!-- Hidden input to hold ID for editing -->

        <label for="studentName">Name</label>
        <input type="text" name="name" class="studentName" required>

        <label for="studentGender">Gender</label>
        <select name="gender" class="studentGender" required>
          <option value="Male">Male</option>
          <option value="Female">Female</option>
        </select>

        <label for="studentHobbies">Hobbies</label>
        <input type="text" name="hobbies" class="studentHobbies" required>

        <label for="studentAge">Age</label>
        <input type="number" name="age" class="studentAge" required>

        <label for="studentAge">PhoneNumber</label>
        <input type="text" name="phoneNumber" class="studentPhoneNumber" required>

        <label for="studentAge">Email</label>
        <input type="text" name="email" class="studentEmail" required>

        <button type="submit" class="saveStudentBtn">Save Student</button>
      </form>
    </div>
  </div>

  <!-- 引入Moment.js -->
  <script src="https://momentjs.cn/downloads/moment.js"></script>
  <script>
    // Initial student data
    // 创建原始数据数组
    // const students = [
    //   {
    //     id: 1, name: 'Alice', gender: 'Female', hobbies: 'Reading', age: 20, phoneNumber: '18370431653', email: '96130@qq.com', createTime: 1723794736584, updateTime: 1723794736584,
    //   },
    //   {
    //     id: 2, name: 'Bob', gender: 'Male', hobbies: 'Sports', age: 22, phoneNumber: '19310264748', email: 'g0015@163.com', createTime: 1723794736584, updateTime: 1723794736584,
    //   },
    //   {
    //     id: 3, name: 'Charlie', gender: 'Male', hobbies: 'Gaming', age: 21, phoneNumber: '15932844285', email: '3123@outlook.com', createTime: 1723794736584, updateTime: 1723794736584,
    //   }
    // ];
    // localStorage.setItem('students', JSON.stringify(students))

    // 拿本地数据
    const students = JSON.parse(localStorage.getItem('students'))

    // 定义手机号验证正则
    const phoneReg = /^(?:(?:\+|00)86)?1\d{10}$/
    // 定义邮箱验证正则
    const emailReg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

    // 定义是否正在编辑的标志
    let isEditing = false; // Flag to check if editing

    // Function to render the student table
    // 定义渲染学生表格函数
    function renderTable(searchValue = '') {
      // 获取.studentTable tbody dom 对象
      const tbody = document.querySelector('.studentTable tbody');
      // 清理原数据
      tbody.innerHTML = ''; // Clear the table body

      // 新渲染方法
      const filteredStudents = searchValue ? students.filter(student => student.name.toLowerCase().includes(searchValue.toLowerCase())) : students;
      filteredStudents.forEach(student => {
        const row = document.createElement('tr');
        // Moment.js方法
        let createTime = moment(student.createTime);
        createTime = createTime.format('YYYY-MM-DD HH:mm:ss');
        let updateTime = moment(student.updateTime);
        updateTime = updateTime.format('YYYY-MM-DD HH:mm:ss');
        // 写html
        row.innerHTML = `
                    <td><input type="checkbox" class="selectStudent" data-id="${student.id}"></td>
                    <td>${student.id}</td>
                    <td>${student.name}</td>
                    <td>${student.gender}</td>
                    <td>${student.hobbies}</td>
                    <td>${student.age}</td>
                    <td>${student.phoneNumber}</td>
                    <td>${student.email}</td>
                    <td>${createTime}</td>
                    <td>${updateTime}</td>
                    <td>
                        <button onclick="openEditModal(${student.id})">Edit</button>
                        <button onclick="deleteStudent(${student.id})">Delete</button>
                    </td>
                `;
        // 添加写好的html结构
        tbody.appendChild(row);
      });

      // students.forEach(student => {
      //   const row = document.createElement('tr');
      //   let createTime = moment(student.createTime);
      //   createTime = createTime.format('YYYY-MM-DD HH:mm:ss');
      //   let updateTime = moment(student.updateTime);
      //   updateTime = updateTime.format('YYYY-MM-DD HH:mm:ss');
      //   row.innerHTML = `
      //               <td><input type="checkbox" class="selectStudent" data-id="${student.id}"></td>
      //               <td>${student.id}</td>
      //               <td>${student.name}</td>
      //               <td>${student.gender}</td>
      //               <td>${student.hobbies}</td>
      //               <td>${student.age}</td>
      //               <td>${student.phoneNumber}</td>
      //               <td>${student.email}</td>
      //               <td>${createTime}</td>
      //               <td>${updateTime}</td>
      //               <td>
      //                   <button onclick="openEditModal(${student.id})">Edit</button>
      //                   <button onclick="deleteStudent(${student.id})">Delete</button>
      //               </td>
      //           `;
      //   tbody.appendChild(row);
      // });

    }

    // Function to handle "Select All" checkbox
    // 多选框全选
    document.querySelector('.selectAll').addEventListener('change', function () {
      const checkboxes = document.querySelectorAll('.selectStudent');
      checkboxes.forEach(checkbox => {
        checkbox.checked = this.checked;
      });
    });

    // Function to open the modal for editing student information
    // 打开编辑模态框
    function openEditModal(id) {
      const student = students.find(s => s.id === id);
      if (student) {
        document.querySelector('.modalTitle').textContent = 'Edit Student';
        document.querySelector('.studentIdToEdit').value = student.id;
        document.querySelector('[name="name"]').value = student.name;
        document.querySelector('[name="gender"]').value = student.gender;
        document.querySelector('[name="hobbies"]').value = student.hobbies;
        document.querySelector('[name="age"]').value = student.age;
        document.querySelector('[name=phoneNumber]').value = student.phoneNumber
        document.querySelector('[name=email]').value = student.email
        document.querySelector('.studentModal').style.display = 'block';
        isEditing = true;
      }
    }

    // Function to handle form submission
    // 处理表单提交
    document.querySelector('.studentForm').addEventListener('submit', function (event) {
      event.preventDefault(); // Prevent default form submission 
      // 实例化Date对象
      const date = new Date()

      const formData = new FormData(this);
      const data = Object.fromEntries(formData.entries());

      const id = document.querySelector('.studentIdToEdit').value;

      if (data.name && data.gender && data.hobbies && data.age && phoneReg.test(data.phoneNumber) && emailReg.test(data.email)) {
        if (isEditing) {
          // Update existing student
          const student = students.find(s => s.id === parseInt(id));
          if (student) {
            student.name = data.name;
            student.gender = data.gender;
            student.hobbies = data.hobbies;
            student.age = parseInt(data.age);
            student.phoneNumber = data.phoneNumber
            student.email = data.email
            student.updateTime = date.getTime()
            localStorage.setItem('students', JSON.stringify(students))
          }
          isEditing = false;
        } else {
          // Add new student
          students.push({
            id: students.length ? students[students.length - 1].id + 1 : 1,
            name: data.name,
            gender: data.gender,
            hobbies: data.hobbies,
            age: parseInt(data.age),
            phoneNumber: data.phoneNumber,
            email: data.email,
            createTime: date.getTime()
          });
          localStorage.setItem('students', JSON.stringify(students))
        }

        renderTable();
        document.querySelector('.studentModal').style.display = 'none';
        clearModal();
      } else {
        alert('Please fill in all fields.');
      }

    });

    // Function to clear modal inputs
    // 清除模态框输入
    function clearModal() {
      document.querySelector('.studentForm').reset();
      document.querySelector('.studentIdToEdit').value = '';
    }

    // Function to delete a student
    // 删除学生
    function deleteStudent(id) {
      const index = students.findIndex(s => s.id === id);
      if (index !== -1) {
        students.splice(index, 1);
        localStorage.setItem('students', JSON.stringify(students))
        renderTable();
      }
    }

    // Open modal for adding a new student
    document.querySelector('.openModalBtn').addEventListener('click', function () {
      document.querySelector('.modalTitle').textContent = 'Add New Student';
      document.querySelector('.studentModal').style.display = 'block';
      isEditing = false;
    });

    // Initial table rendering
    renderTable();

    // Close the modal when clicking outside of it
    // 关闭模态框
    window.onclick = function (event) {
      const modal = document.querySelector('.studentModal');
      if (event.target === modal) {
        modal.style.display = 'none';
        clearModal();
      }
    };


    // 使用 name 检索数据，无检索关键词直接点击搜索按钮则默认检索所有数据
    // 绑定事件
    document.querySelector('.search').addEventListener('click', function () {
      const searchValue = document.querySelector('.searchname').value.trim()
      renderTable(searchValue)
    })


    // 本地存储
    localStorage.setItem('students', JSON.stringify(students))


    // 0. 搞懂每一行代码 ，打上注释
    // 1. 修正模态框布局样式和整体bug样式，尽量让按钮 Input框美观些（1）提示：盒子模型计算
    // 2. 学生信息增加手机号和邮箱字段列 并在添加和修改的时候验证手机号和邮箱格式-正则
    // 3. 学生信息增加 创建时间和修改时间列 格式【YYYY-MM-DD HH:mm:ss】
    // 4. 列表的右上角增加 input框，搜索按钮，可以使用 name 检索数据，无检索关键词直接点击搜索按钮则默认检索所有数据
    // 5. 讲学生信息存入 localStorage ，使用JSON格式，关闭打开浏览器数据依然在
    // 6. 多选按钮样式和实际选择数据同步（可放最后）


  </script>

</body>

</html>